﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using SocialFront.Entities;

namespace SocialFront
{
    public class Utilities
    {
        /*public static bool CreateMemberInUmbraco(string userName, string password, string emailAddress, DateTime dob, bool newsletter, out string outMessage)//, string firstName, string surname, string dob)
        {

            bool isUserCreated;
            try
            {
                MemberType communityMemberType = new MemberType(Convert.ToInt32(Config.sfMemberType));

                Member newMember = Member.MakeNew(userName, communityMemberType,
                                                  new umbraco.BusinessLogic.User(0));

                newMember.Email = emailAddress;
                newMember.Password = password;
                newMember.LoginName = userName;

                newMember.getProperty("newsletter").Value = newsletter;
                newMember.getProperty("dateOfBirth").Value = dob.ToString("yyyy-MM-dd");

                // Add user to the Member Admin Group
                newMember.AddGroup(MemberGroup.GetByName("Member").Id);

                newMember.Save();

                isUserCreated = true;
                outMessage = "Umbraco Created!";
            }
            catch (Exception ex)
            {
                isUserCreated = false;
                Log.Add(LogTypes.Error, -1, ex.Message);
                outMessage = "ERROR:" + ex.ToString();
            }
            return isUserCreated;
        }*/

        /// <summary>
        /// This class will recieve and uploaded file and save it to a directory specified in the web.config
        /// </summary>
        /// <param name="uploadControl">Uploaded file</param>
        /// <returns></returns>
        /*public static Media SaveUploadedFile(FileUpload uploadControl, int mediaFolderAliasId)
        {
            string _text = "";
            Media m = null;
            if (uploadControl.PostedFile != null)
            {
                if (uploadControl.PostedFile.FileName != "")
                {
                    // Find filename
                    _text = uploadControl.PostedFile.FileName;

                    string filename = _text.Substring(_text.LastIndexOf("\\") + 1, _text.Length - _text.LastIndexOf("\\") - 1).ToLower();

                    // create the Media Node
                    // TODO:  get parent id for current category - as selected by user (see below)
                    // - for now just stick these in the media root :: node = -1
                    m = Media.MakeNew(
                        filename, MediaType.GetByAlias("image"), User.GetUser(0), mediaFolderAliasId);

                    // Create a new folder in the /media folder with the name /media/propertyid
                    string mediaRootPath = "/media/"; // This should be refactored so the upload location can be speficied in the web.config
                    string storagePath = HttpContext.Current.Request.PhysicalApplicationPath + mediaRootPath + m.Id.ToString();
                    System.IO.Directory.CreateDirectory(storagePath);
                    string _fullFilePath = storagePath + "\\" + filename;
                    uploadControl.PostedFile.SaveAs(_fullFilePath);

                    // Save extension
                    string orgExt = ((string)_text.Substring(_text.LastIndexOf(".") + 1, _text.Length - _text.LastIndexOf(".") - 1));
                    orgExt = orgExt.ToLower();
                    string ext = orgExt.ToLower();
                    try
                    {
                        m.getProperty("umbracoExtension").Value = ext;
                    }
                    catch { }

                    // Save file size
                    try
                    {
                        FileInfo fi = new FileInfo(_fullFilePath);
                        m.getProperty("umbracoBytes").Value = fi.Length.ToString();
                    }
                    catch { }

                    // Check if image and then get sizes, make thumb and update database
                    if (",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + ext + ",") > 0)
                    {
                        int fileWidth;
                        int fileHeight;

                        FileStream fs = new FileStream(_fullFilePath,
                            FileMode.Open, FileAccess.Read, FileShare.Read);

                        System.Drawing.Image image = System.Drawing.Image.FromStream(fs);
                        fileWidth = image.Width;
                        fileHeight = image.Height;
                        fs.Close();
                        try
                        {
                            m.getProperty("umbracoWidth").Value = fileWidth.ToString();
                            m.getProperty("umbracoHeight").Value = fileHeight.ToString();
                        }
                        catch
                        {
                            // Add logging of errors to the umbraco database.
                            //umbraco
                        }

                        // Generate thumbnails
                        //string fileNameThumb = _fullFilePath.Replace("." + orgExt, "_thumb");
                        //generateThumbnail(image, 100, fileWidth, fileHeight, _fullFilePath, ext, fileNameThumb + ".jpg");

                        image.Dispose();
                    }
                    string mediaPath = "/media/" + m.Id.ToString() + "/" + filename;

                    m.getProperty("umbracoFile").Value = mediaPath;
                    m.XmlGenerate(new XmlDocument());
                }
            }

            // return the media...
            return m;
        }/

        /*protected void generateThumbnail(System.Drawing.Image image, int maxWidthHeight, int fileWidth, int fileHeight, string fullFilePath, string ext, string thumbnailFileName)
        {
            // Generate thumbnail
            float fx = (float)fileWidth / (float)maxWidthHeight;
            float fy = (float)fileHeight / (float)maxWidthHeight;
            // must fit in thumbnail size
            float f = Math.Max(fx, fy); //if (f < 1) f = 1;
            int widthTh = (int)Math.Round((float)fileWidth / f); int heightTh = (int)Math.Round((float)fileHeight / f);

            // fixes for empty width or height
            if (widthTh == 0)
                widthTh = 1;
            if (heightTh == 0)
                heightTh = 1;

            // Create new image with best quality settings
            Bitmap bp = new Bitmap(widthTh, heightTh);
            Graphics g = Graphics.FromImage(bp);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;

            // Copy the old image to the new and resized
            Rectangle rect = new Rectangle(0, 0, widthTh, heightTh);
            g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

            // Copy metadata
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo codec = null;
            for (int i = 0; i < codecs.Length; i++)
            {
                if (codecs[i].MimeType.Equals("image/jpeg"))
                    codec = codecs[i];
            }

            // Set compresion ratio to 90%
            EncoderParameters ep = new EncoderParameters();
            ep.Param[0] = new EncoderParameter(Encoder.Quality, 90L);

            // Save the new image
            bp.Save(thumbnailFileName, codec, ep);
            bp.Dispose();
            g.Dispose();

        }
        */

        public static List<Entities.Tag> ConvertCsvToTags(string csvInput)
        {
            string[] csvSplit = csvInput.Split(',');
            List<Entities.Tag> tags = new List<Tag>();
            foreach (string s in csvSplit)
            {
                if (!string.IsNullOrEmpty(s.Trim()))
                    tags.Add(new Tag() {Name = s});
            }
            return tags;
        }

        public static string GetBodyClasses(HttpRequest request)
        {
            StringBuilder output = new StringBuilder();
            output.AppendFormat("{0}", request.Browser.Browser);
            output.AppendFormat(" {0}{1}", request.Browser.Browser, request.Browser.MajorVersion);
            output.AppendFormat(" {0}", request.Browser.Platform);
            return output.ToString();
        }

        public static void AddTinyMce()
        {
            Page currentPage = ((Page)HttpContext.Current.Handler);
            currentPage.ClientScript.RegisterClientScriptInclude("TinyMceCore", currentPage.ResolveUrl("~/umbraco_client/tinymce3/tiny_mce.js"));
            currentPage.ClientScript.RegisterClientScriptInclude("TinyMce", currentPage.ResolveUrl("~/scripts/LoadTinyMce.js"));
        }
    }
}

